"use strict";

const Service = require("egg").Service;

class DictItemService extends Service {
  async index(dict_id, { page, pageSize } = { page: 1, pageSize: 10 }) {
    const { ctx, app } = this;

    // 构建查询条件
    const where = {};

    // 构建or条件数组
    const orConditions = [];

    if (dict_id) {
      orConditions.push({
        dict_id: {
          [app.Sequelize.Op.like]: `%${dict_id}%`,
        },
      });
    }

    // 只有当orConditions数组不为空时，才添加到where条件中
    if (orConditions.length > 0) {
      where[app.Sequelize.Op.or] = orConditions;
    }

    const result = await ctx.model.DictItem.findAndCountAll({
      where,
      order: [["created_at", "DESC"]], // Sort by sort field and createdAt
      offset: (page - 1) * pageSize,
      limit: pageSize,
    });
    return {
      rows: result.rows,
      count: result.count,
    };
  }

  async create(dictItemData) {
    const { ctx } = this;

    const newDictItem = await ctx.model.DictItem.create(dictItemData);
    return newDictItem;
  }

  async destroy(id) {
    const { ctx } = this;
    const result = await ctx.model.DictItem.destroy({
      where: { id },
    });
    return result > 0; // 返回是否删除成功
  }

  async batchDelete(ids) {
    const { ctx } = this;
    const result = await ctx.model.DictItem.destroy({
      where: { id: ids },
    });
    return result > 0; // 返回是否删除成功
  }

  async update(id, dictItemData) {
    const { ctx } = this;
    const [updatedRows] = await ctx.model.DictItem.update(dictItemData, {
      where: { id },
    });
    return updatedRows > 0; // 返回是否更新成功
  }

  async countByTypeId(dict_id) {
    const { ctx } = this;
    return await ctx.model.DictItem.count({
      where: { dict_id: dict_id },
    });
  }

  async indexByDictId(dict_id) {
    const { ctx } = this;
    return await ctx.model.DictItem.findAll({
      where: { dict_id: dict_id },
    });
  }
}

module.exports = DictItemService;
